<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pagParams.page"
                :page-sizes="[2, 5, 7, 9]"
                :page-size="pagParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />

            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :title="isEdit ? '编辑' : '新增'"
        :visible.sync="showDialog"
        @close="hColse"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { RoleGetdata, RoleAdddata, Roledeldata, Rolelookdata, RoleAssignPremdata } from '@/api/settings'
export default {
  data() {
    return {
      isEdit: false,
      showDialog: false,
      list: [],
      pagParams: {
        page: 1,
        pagesize: 2
      },
      total: 0,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    // 退出清空表单
    hColse() {
      this.$refs.roleForm.resetFields()
    },
    // isEdit
    hEdit(id) {
      this.isEdit = true
      this.showDialog = true
      this.loadRoleDetail(id) // 当选中编辑按钮时 触发 loadRoleDetail（id）函数
    },
    // hAdd
    hAdd() {
      this.isEdit = false
      this.showDialog = true
    },
    async loadRoleDetail(id) {
      try {
        const { data: res } = await Rolelookdata(id)
        console.log(res)
        if (res.code === 10000) {
          this.roleForm = res.data
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 获取员工信息
    async loadRoles() {
      const res = await RoleGetdata(this.pagParams)
      console.log(res)
      if (res.code !== 10000) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.list = res.data.rows
      this.total = res.data.total
      // console.log(this.list)
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // this.pagParams.page = 1
      this.pagParams.pagesize = val
      this.loadRoles()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.pagParams.page = val
      this.loadRoles()
    },
    // 表单提交
    async doAdd() {
      try {
        const res = await RoleAdddata(this.roleForm)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.total++ // 每添加一个数据 total 就自加1
        const maxPage = Math.ceil(this.total / this.pagParams.pagesize) // Math.ceil向上取整 所有的数据 除以 当前页显示的数据 最大的页面 例如 数据有10条 当前显示页面2 条  10/2 = 5 就是最大的页面
        this.pagParams.page = maxPage
        this.loadRoles()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    async doEdit() {
      try {
        const res = await RoleAssignPremdata(this.roleForm)
        console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.loadRoles()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    hSubmit() {
      this.$refs.roleForm.validate(val => {
        if (!val) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 删除
    hDel(id) {
      this.$confirm('确定删除？').then(async() => {
        const res = await Roledeldata(id)
        if (res.code !== 10000) return this.$message.error(res.message)
        if (this.list.length === 1) { // 判断当前页所有数据   的数组长度
          this.pagParams.page-- // 如果数组长度 为1的时候删除就将 page 自身减一
          if (this.pagParams.page <= 0) { // 再判断 如果 这个页面中的 页面小于 0 时 就将 这个页面改为1
            this.pagParams.page = 1
          }
        }
        this.$message.success(res.message)
        this.loadRoles()
      }).catch(err => err)
    }
  }
}
</script>
